package com.king.tv.mvp.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Layout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.king.base.util.LogUtils;
import com.king.base.util.ToastUtils;
import com.king.tv.R;
import com.king.tv.bean.Room;
import com.king.tv.http.ApiConfig;
import com.king.tv.mvp.base.BaseFragment;
import com.king.tv.mvp.presenter.RoomPresenter;
import com.king.tv.mvp.view.IRoomView;
import com.king.view.flutteringlayout.FlutteringLayout;

import butterknife.BindView;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.BlurTransformation;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

/**
 * @author Jenly <a href="mailto:jenly1314@gmail.com">Jenly</a>
 * @since 2017/5/2
 */

public class FullRoomFragment extends BaseFragment<IRoomView, RoomPresenter> implements IRoomView {

    @BindView(R.id.rlAnchorInfo)
    View rlAnchorInfo;
    @BindView(R.id.civAvatar)
    ImageView civAvatar;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvFans)
    TextView tvFans;
    @BindView(R.id.ivCover)
    ImageView ivCover;
    @BindView(R.id.frameVideo)
    FrameLayout frameVideo;
    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.tvAccount)
    TextView tvAccount;
    @BindView(R.id.ivInput)
    ImageView ivInput;
    @BindView(R.id.ivFollow)
    ImageView ivFollow;
    @BindView(R.id.ivGift)
    ImageView ivGift;
    @BindView(R.id.ivShare)
    ImageView ivShare;
    @BindView(R.id.ivMessage)
    ImageView ivMessage;
    @BindView(R.id.rlRoomInfo)
    LinearLayout rlRoomInfo;
    @BindView(R.id.videoContent)
    RelativeLayout videoContent;
    @BindView(R.id.flutteringLayout)
    FlutteringLayout flutteringLayout;
    @BindView(R.id.btnHeart)
    Button btnHeart;
    @BindView(R.id.pb_Video)
    ProgressBar progressBar;
    @BindView(R.id.ivfulltx1)
    ImageView iv1;
    @BindView(R.id.ivfulltx2)
    ImageView iv2;
    @BindView(R.id.ivfulltx3)
    ImageView iv3;
    @BindView(R.id.ivfulltx4)
    ImageView iv4;
    @BindView(R.id.ivfulltx5)
    ImageView iv5;
    @BindView(R.id.ivfulltx6)
    ImageView iv6;
    @BindView(R.id.ivfulltx7)
    ImageView iv7;
    private String uid;

    private String coverUrl;

    private String fans;

    private VideoFragment videoFragment;

    public static FullRoomFragment newInstance(String uid,String coverUrl) {

        Bundle args = new Bundle();
        FullRoomFragment fragment = new FullRoomFragment();
        fragment.uid = uid;
        fragment.coverUrl = coverUrl;
//        fragment.fans = num;
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    @Override
    public int getRootViewId() {
        return R.layout.fragment_full_room;
    }

    @Override
    public void initUI() {
        initVideoTop();
//        tvAccount.setText(String.format(getString(R.string.qm_account),uid));
//          tvAccount.setText(uid);
//          Glide.with(this).load(uid).centerCrop().apply(bitmapTransform(new BlurTransformation(context,18,3))).diskCacheStrategy(DiskCacheStrategy.RESOURCE).into(ivCover);
//        Glide.with(this).setDefaultRequestOptions(
//                        new RequestOptions()
//                                .frame(1000000)//单位微秒
//                                .centerCrop()
//                                .error(R.mipmap.live_default)
//                                .placeholder(R.mipmap.live_default) ).load(uid).into(ivCover);
    }

    @Override
    public void initData() {
        getPresenter().enterRoom(uid,true);
    }


    @Override
    public RoomPresenter createPresenter() {
        return new RoomPresenter(getApp());
    }


    @Override
    public void showProgress() {

    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void enterRoom(Room room) {

        LogUtils.d("enterRoom:" + room.getUid());
        updateAnchorInfo(room);
    }

    @Override
    public void playUrl(String url) {
        LogUtils.d("playUrl:" + url);

        if (videoFragment == null) {
            videoFragment = VideoFragment.newInstance(url,true);
        }
        replaceChildFragment(R.id.frameVideo, videoFragment);
        clickHeart();
        progressBar.setVisibility(View.GONE);
    }


    private void updateAnchorInfo(Room room){
        if(room!=null){
            rlAnchorInfo.setVisibility(View.VISIBLE);
            Glide.with(this).load(room.getAvatar()).placeholder(R.drawable.mine_default_avatar).error(R.drawable.mine_default_avatar).centerCrop().transition(DrawableTransitionOptions.withCrossFade(500)).diskCacheStrategy(DiskCacheStrategy.RESOURCE).into(civAvatar);
            tvName.setText(room.getNick());
            tvFans.setText(String.format(getString(R.string.fans_num),room.getFollow()));

        }
    }


    private void clickInput(){

    }

    private void clickFollow(){
        startLogin();
    }

    private void clickGift(){

    }

    private void clickShare(){

    }

    private void clickMessage(){
        startLogin();
    }

    private void clickHeart(){
        flutteringLayout.addHeart();
    }


    @OnClick({R.id.ivBack, R.id.ivInput, R.id.ivFollow, R.id.ivGift, R.id.ivShare, R.id.ivMessage,R.id.btnHeart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivInput:
                clickInput();
                break;
            case R.id.ivFollow:
                clickFollow();
                break;
            case R.id.ivGift:
                clickGift();
                break;
            case R.id.ivShare:
                clickShare();
                break;
            case R.id.ivMessage:
                clickMessage();
                break;
            case R.id.btnHeart:
                clickHeart();
                break;
        }
    }

    /**
     * 初始化播放界面顶部显示
     */
    private void initVideoTop() {
        if(!TextUtils.isEmpty(coverUrl)){
            String picurl = ApiConfig.BASE_URL+coverUrl;
            Glide.with(getContext()).load(picurl).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv5);
        }else{
            Glide.with(getContext()).load(R.mipmap.ic_launcher1).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv5);
        }
        int[] pic = {R.drawable.tximage1,R.drawable.tximage2,R.drawable.tximage3,R.drawable.tximage4,R.drawable.tximage5,R.drawable.tximage6,R.drawable.tximage7,R.drawable.tximage8};
        int[] num = randomCommon(0,7,6);
        Glide.with(getContext()).load(pic[num[0]]).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv1);
        Glide.with(getContext()).load(pic[num[1]]).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv2);
        Glide.with(getContext()).load(pic[num[2]]).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv3);
        Glide.with(getContext()).load(pic[num[3]]).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv4);
        Glide.with(getContext()).load(pic[num[4]]).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv6);
        Glide.with(getContext()).load(pic[num[5]]).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv7);
    }

    /**
     * 随机生成n个不重复的数
     * @param min
     * @param max
     * @param n
     * @return
     */
    private int[] randomCommon(int min, int max, int n){
        // 有效性判断
        if (n > (max - min + 1) || max < min) {
            return null;
        }
        // 按随机个数声明存放数组
        int[] result = new int[n];
        // 统计生成个数
        int count = 0;
        // 生成个数小于n之前，一直生成
        while(count < n) {
            // 在指定范围内生成随机数
            int num = (int) (Math.random() * (max - min)) + min;
            // 重复标记
            boolean flag = true;
            // 将生成的随机数与数组中已生成的数作比较
            for (int j = 0; j < n; j++) {
                // 重复则标记
                if(num == result[j]){
                    flag = false;
                    break;
                }
            }
            // 不重复则加入数组
            if(flag) {
                result[count] = num;
                // 生成个数累加
                count++;
            }
        }
        return result;
    }
}
